/*********************************************************
          File Name:control.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 26 Jun 2015 05:13:39 PM CST
**********************************************************/

#include "control.h"
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int pidfile(char *pid_file, pid_t * pid, char op)
{
    FILE *fp = NULL;

    if (op == 'r') {
        if ((fp = fopen(pid_file, "r")) == NULL)
            return -1;
        if (fscanf(fp, "%d", pid) == -1)
            return -1;
    } else {
        unlink(pid_file);       /* ignore errors */
        if ((fp = fopen(pid_file, "w")) == NULL)
            return -1;

        if (fprintf(fp, "%d", *pid) == -1)
            return -1;
    }
    fclose(fp);
    return 0;
}

void parse_cmd(char *pid_file, int argc, char **argv)
{
    pid_t pppid;

    if (argc == 1) {
        int fd = open (pid_file, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        if(fd == -1) {
            perror("open");
            exit(1);
        }

        struct flock lock;
        memset(&lock, 0, sizeof(lock));
        lock.l_type = F_WRLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;

        if (fcntl(fd, F_SETLK, &lock) == -1) {
            close(fd);
            perror("fcntl");
            fprintf(stderr, "A instance is running...\n");
            exit(1);
        }

        char buf[10] = {0};
        sprintf(buf, "%d", getpid());
        write(fd, buf, strlen(buf));
        return;
    }

    if (strcmp(argv[1], "restart") == 0) {
        if (pidfile(pid_file, &pppid, 'r') == -1) {
            fprintf(stderr, "%s", strerror(errno));
            exit(1);
        }
        if (kill(pppid, SIGHUP) == -1)
            fprintf(stderr, "sending restart signal failed, exit...\n");
        else
            printf("restarted\n");
    } else if (strcmp(argv[1], "stop") == 0) {
        if (pidfile(pid_file, &pppid, 'r') == -1) {
            fprintf(stderr, "%s", strerror(errno));
            exit(1);
        }
        printf("pid = %d\t self = %d\n", pppid, getpid());
        if (kill(pppid, SIGTERM) == -1)
            fprintf(stderr, "sending exit signal failed, exit...\n");
        else
            printf("stopped\n");
    } else
        fprintf(stderr, "Usage:%s [restart|stop]\n", argv[0]);
    exit(0);
}
